﻿using Ec_System.Facade.Web;
using Ec_System.WebUI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Security.Application;
using Ec_System.Models.Web;
using Newtonsoft.Json;

namespace Ec_System.WebUI.Areas.Web.Controllers
{
    public class ShopCartController : Controller
    {
        LoginViewModel userLoginInfo = new UserHelp().TryGetUserInfo();
        ShopCartFacade shopCartFacade = new ShopCartFacade();
        CustomerFacade customerFacade = new CustomerFacade();
        // GET: Web/ShopCart
        public ActionResult Index()
        {
            if(userLoginInfo == null)
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web" });
            }

            var model = shopCartFacade.GetShopCartListByLoginID((userLoginInfo.LoginID));
            return View(model);
        }

        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddShopCart(FormCollection formCollection)
        {
            int pID = int.Parse( Sanitizer.GetSafeHtmlFragment(formCollection["hid_ProductID"]));
            int num = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["txt_Num"]));

            if(userLoginInfo != null)
            {
                ShopCartData cart = new ShopCartData()
                {
                    ProductID = pID,
                    ProductQty = num,
                    LoginID = userLoginInfo.LoginID
                };
                //添加到购物车, 存入缓存
                shopCartFacade.AddShopCart(cart);

                return RedirectToAction("Index", new { controller = "ShopCart", area = "Web" });
            }
            else
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web", ReturnUrl = "Item/" + pID });
            }
        }

        /// <summary>
        ///从购物车删除指定的Product
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
       [HttpPost]
       [ValidateAntiForgeryToken]
       public ActionResult DeleteShopCart(FormCollection formCollection)
        {
            if (userLoginInfo == null)
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web" });
            }

            int pID = int.Parse(Sanitizer.GetSafeHtmlFragment(formCollection["pID"]));
            var model = shopCartFacade.RemoveShopCartByProductID(pID, userLoginInfo.LoginID);

            return View("Index", model);
        }

        /// <summary>
        /// 确定订单
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConfirmCar(FormCollection formCollection)
        {
            if(userLoginInfo != null && Request.IsAuthenticated)
            {
                string json = Sanitizer.GetSafeHtmlFragment(formCollection["items"]);
                json = json.Replace("pid", "ProductID").Replace("num", "ProductQty");
                json = "[" + json.TrimEnd(',') + "]"; //[{},{}]

                var newCartList = JsonConvert.DeserializeObject<List<ShopCartData>>(json);

                //更新购物车
                newCartList = shopCartFacade.UpdateShopCart(newCartList, userLoginInfo.LoginID);
                //检查库存情况
                newCartList = shopCartFacade.PreCheckOut(newCartList);
                if(newCartList.Where(c => c.StoreStatus == 0).Count() > 0)
                {
                    return View("Index", newCartList);
                }
                else
                {
                    return RedirectToAction("CheckOut");
                }
            }
            else
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web" });
            }
        }

        /// <summary>
        /// 结算页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CheckOut()
        {
            if(userLoginInfo == null || !Request.IsAuthenticated)
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web" });
            }

            var model = customerFacade.GetUserInfoByLoginID(userLoginInfo.LoginID);
            ViewData["totalMoney"] = shopCartFacade.GetShopCartListByLoginID(userLoginInfo.LoginID).Sum(p => p.RowMoney);

            return View(model);
        }
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult CheckOut(FormCollection formCollection)
        {          
            if (userLoginInfo == null || !Request.IsAuthenticated)
            {
                return RedirectToAction("UserLogin", new { controller = "Customer", area = "Web" });
            }
            var loginID = userLoginInfo.LoginID;

            string adrID = Sanitizer.GetSafeHtmlFragment(formCollection["adrID"]);
            string shipType = Sanitizer.GetSafeHtmlFragment(formCollection["shipType"]);
            string payID = Sanitizer.GetSafeHtmlFragment(formCollection["PayID"]);
            string payPwd = Sanitizer.GetSafeHtmlFragment(formCollection["pwd"]);

            List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
            keyValues.Add(new KeyValuePair<string, string>("adrID", adrID));
            keyValues.Add(new KeyValuePair<string, string>("payID", payID));
            keyValues.Add(new KeyValuePair<string, string>("shipType", shipType));
            keyValues.Add(new KeyValuePair<string, string>("loginID", loginID));
            keyValues.Add(new KeyValuePair<string, string>("payPwd", payPwd));

            var cartList = shopCartFacade.GetShopCartListByLoginID(loginID);
            var result = shopCartFacade.CheckOut(cartList, keyValues);

            if (result == 1)
            {
                return View("Success");
            }
            else
            {
                TempData["payPwdError"] = "支付密码错误";
                return RedirectToAction("CheckOut");
            }

        }

        [HttpGet]
        public ViewResult Success()
        {
            return View();
        }

    }
}